package com.sywb.chuangyebao.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.czt.mp3recorder.MP3Player;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.Answer;
import com.sywb.chuangyebao.bean.Question;
import com.sywb.chuangyebao.bean.QuestionInfo;
import com.sywb.chuangyebao.view.BindMobileActivity;
import com.sywb.chuangyebao.view.UserIndexActivity;
import com.sywb.chuangyebao.view.WebActivity;
import com.sywb.chuangyebao.view.dialog.BindMobiletDialog;
import com.sywb.chuangyebao.view.dialog.SexSelectDialog;

import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.db.DbManager;
import org.bining.footstone.log.Logger;
import org.bining.footstone.mvp.IView;
import org.bining.footstone.presenter.BasePresenter;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.FileUtils;
import org.bining.footstone.utils.SharedUtils;
import org.bining.footstone.utils.ToastUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * Created by 55341 on 2018/1/24.
 */
public class Utils {

    public static void hideSoftKeyborad(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
        }
    }

    public static boolean checkIsLogin() {
        if (!SharedUtils.getBoolean(Constants.USERISLOGIN, false)) {
            RxBus.get().post(Constants.HTTP_SSO_LOGIN, Constants.HTTP_SSO_LOGIN);
            return false;
        } else return true;
    }

    public static boolean checkMobileVerify() {
        return SharedUtils.getBoolean(Constants.USERMOBILEVERIFY, false);
    }

    public static boolean checkIsNext(FragmentManager fragmentManager) {
        if (checkIsLogin()) {
            if (checkMobileVerify()) {
                return true;
            } else {
                BindMobiletDialog dialog = BindMobiletDialog.newInstance();
                dialog.setOnItemListener(new BindMobiletDialog.OnItemListener() {
                    @Override
                    public void onResult(Activity mActivity) {
                        Logger.e("BindMobiletDialog onResult");
                        if (mActivity != null && !mActivity.isFinishing()) {
                            mActivity.startActivity(new Intent(mActivity, BindMobileActivity.class));
                            mActivity.overridePendingTransition(org.bining.footstone.R.anim.view_in_from_right, org.bining.footstone.R.anim.view_out_to_left);
                        }
                    }
                });
                dialog.show(fragmentManager, "BindMobile");
            }
        }
        return false;
    }

    public static void setFolllowView(Activity mActivity, boolean isFollowed, TextView tvAddFocus) {
        if (isFollowed) {
            tvAddFocus.setBackgroundResource(R.drawable.round3_pie_gray_light);
            tvAddFocus.setTextColor(ContextCompat.getColor(mActivity, R.color.colorGray));
            tvAddFocus.setText(R.string.btn_attentioned);
        } else {
            tvAddFocus.setBackgroundResource(R.drawable.round_pie_msg_unread);
            tvAddFocus.setText(R.string.add_focus);
            tvAddFocus.setTextColor(ContextCompat.getColor(mActivity, R.color.colorLight));
        }
    }

    public static void goBigPic(Activity mActivity, int i, List<String> pics) {
        //传到展示图片的viewPager
//        Intent intent = new Intent(context, ImagePagerActivity.class);
//        intent.putExtra(ImagePagerActivity.POSITION, 0);
//        intent.putStringArrayListExtra(ImagePagerActivity.IMG_URLS, (ArrayList<String>) pics);
//        context.startActivity(intent);

        List<LocalMedia> localMedias = new ArrayList<>();
        for (String path : pics) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(path);
            localMedias.add(localMedia);
        }

        // 预览图片 可自定长按保存路径
        PictureSelector.create(mActivity).externalPicturePreview(i, FileUtils.getAppDefPath(FileUtils.PATH_IMAGE), localMedias);

    }

    public static void setUserRoleIcon(ImageView ivUserType, int user_group_id) {
        //设置提问人角色类型
        ivUserType.setVisibility(View.VISIBLE);
        switch (user_group_id) {
            case Constants.USER_TYPE_TUTOR:
                ivUserType.setImageResource(R.drawable.icon_teacher);
                break;
            case Constants.USER_TYPE_PROJECT:
                ivUserType.setImageResource(R.drawable.icon_project);
                break;
            case Constants.USER_TYPE_SERVICE:
                ivUserType.setImageResource(R.drawable.icon_service);
                break;
            case Constants.USER_TYPE_V:
                ivUserType.setImageResource(R.drawable.official_icon);
                break;
            default:
                ivUserType.setVisibility(View.GONE);
                break;
        }
    }

    public static void setUserRoleText(TextView ivUserType, int user_group_id) {
        //设置提问人角色类型
        ivUserType.setVisibility(View.VISIBLE);
        switch (user_group_id) {
            case Constants.USER_TYPE_TUTOR:
                ivUserType.setText(R.string.tutor);
                break;
            case Constants.USER_TYPE_PROJECT:
                ivUserType.setText(R.string.project);
                break;
            case Constants.USER_TYPE_SERVICE:
                ivUserType.setText(R.string.service);
                break;
            default:
                ivUserType.setVisibility(View.GONE);
                break;
        }
    }


    public static void setUserRoleIcon(ImageView ivUserType, String user_role) {
        //设置提问人角色类型
        setUserRoleIcon(ivUserType, getUserRole(user_role));
    }

    public static void setUserRoleText(TextView ivUserType, String user_role) {
        setUserRoleText(ivUserType, getUserRole(user_role));
    }


    public static int getUserRole(String user_role) {
        if (!TextUtils.isEmpty(user_role)) {
            HashMap<Integer, String> userRole = JSON.parseObject(user_role, new TypeReference<HashMap<Integer, String>>() {
            });
            if (userRole.containsKey(Constants.USER_TYPE_V)) {
                return Constants.USER_TYPE_V;
            } else if (userRole.containsKey(Constants.USER_TYPE_PROJECT)) {
                return Constants.USER_TYPE_PROJECT;
            } else if (userRole.containsKey(Constants.USER_TYPE_SERVICE)) {
                return Constants.USER_TYPE_SERVICE;
            } else if (userRole.containsKey(Constants.USER_TYPE_TUTOR)) {
                return Constants.USER_TYPE_TUTOR;
            }
        }
        return Constants.USER_TYPE_NORMAL;
    }


    public static void setQuestionAudioItemView(final ViewHolderHelper viewHolderHelper, Activity mActivity, final Question model, String playingAudioUrl, MP3Player mp3Player, boolean isPlaying) {
        viewHolderHelper.setItemChildClickListener(R.id.iv_media_type);
//                            //设置语音背景图片(用户头像)
        ImageView imageFace = viewHolderHelper.getView(R.id.iv_media);
        GlideUtils.getNormalIamgeToUrl(mActivity, model.avatar, imageFace, R.drawable.head_image);
//
//                            //设置语音时长
//        if (model.max > 0) {
//            viewHolderHelper.setText(R.id.tv_audio_time, DateTimeUtils.getMediaTimeNumber(model.max / 1000));
//        } else
        if (!TextUtils.isEmpty(model.audioLength)) {
            if (model.audioLength.contains(":")) {
                viewHolderHelper.setText(R.id.tv_audio_time, model.audioLength);
            } else {
                viewHolderHelper.setText(R.id.tv_audio_time, "00:" + (Integer.valueOf(model.audioLength) > 9 ? model.audioLength : "0" + model.audioLength));
            }
        }

        viewHolderHelper.setImageResource(R.id.iv_media_type, !TextUtils.isEmpty(playingAudioUrl) && !TextUtils.isEmpty(model.audio) && playingAudioUrl.equals(model.audio)
                && mp3Player != null && isPlaying ? R.drawable.stop_video_l : R.drawable.icon_media_audio);

        viewHolderHelper.setText(R.id.tv_current_time, DateTimeUtils.getMediaTimeNumber(model.progress / 1000));
        SeekBar seekBar = viewHolderHelper.getView(R.id.seekbar);
        seekBar.setProgress(model.progress);
        seekBar.setMax(model.max);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                model.progress = seekBar.getProgress();
                viewHolderHelper.setText(R.id.tv_current_time, DateTimeUtils.getMediaTimeNumber(seekBar.getProgress() / 1000));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    public static void setAnswerAudioItemView(final ViewHolderHelper viewHolderHelper, Activity mActivity, final Answer model, String playingAudioUrl, MP3Player mp3Player, boolean isPlaying) {
        viewHolderHelper.setItemChildClickListener(R.id.iv_media_type);
//                            //设置语音背景图片(用户头像)
        ImageView imageFace = viewHolderHelper.getView(R.id.iv_media);
        GlideUtils.getNormalIamgeToUrl(mActivity, model.avatar, imageFace, R.drawable.head_image);
//
//                            //设置语音时长
//        if (model.max > 0) {
        viewHolderHelper.setText(R.id.tv_audio_time, DateTimeUtils.getMediaTimeNumber(model.max / 1000));
//        } else
        if (model.audioLength.contains(":")) {
            viewHolderHelper.setText(R.id.tv_audio_time, model.audioLength);
        } else {
            viewHolderHelper.setText(R.id.tv_audio_time, "00:" + (Integer.valueOf(model.audioLength) > 9 ? model.audioLength : "0" + model.audioLength));
        }
        viewHolderHelper.setImageResource(R.id.iv_media_type, !TextUtils.isEmpty(playingAudioUrl) && !TextUtils.isEmpty(model.audio) && playingAudioUrl.equals(model.audio)
                && mp3Player != null && isPlaying ? R.drawable.stop_video_l : R.drawable.icon_media_audio);

        viewHolderHelper.setText(R.id.tv_current_time, DateTimeUtils.getMediaTimeNumber(model.progress / 1000));
        SeekBar seekBar = viewHolderHelper.getView(R.id.seekbar);
        seekBar.setProgress(model.progress);
        seekBar.setMax(model.max);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                model.progress = seekBar.getProgress();
                viewHolderHelper.setText(R.id.tv_current_time, DateTimeUtils.getMediaTimeNumber(seekBar.getProgress() / 1000));
            }
        });
    }

    public static void setQuestionAudioItemView(final ViewHolderHelper viewHolderHelper, Activity mActivity, final QuestionInfo model, String playingAudioUrl, MP3Player mp3Player, boolean isPlaying) {
        viewHolderHelper.setItemChildClickListener(R.id.iv_media_type);
//                            //设置语音背景图片(用户头像)
        ImageView imageFace = viewHolderHelper.getView(R.id.iv_media);
        GlideUtils.getNormalIamgeToUrl(mActivity, model.owner.getShowAvatar(), imageFace, R.drawable.head_image);
//
//                            //设置语音时长
//        if (model.max > 0) {
//            viewHolderHelper.setText(R.id.tv_audio_time, DateTimeUtils.getMediaTimeNumber(model.max / 1000));
//        } else
        if (!TextUtils.isEmpty(model.audioLength)) {
            if (model.audioLength.contains(":")) {
                viewHolderHelper.setText(R.id.tv_audio_time, model.audioLength);
            } else {
                viewHolderHelper.setText(R.id.tv_audio_time, "00:" + (Integer.valueOf(model.audioLength) > 9 ? model.audioLength : "0" + model.audioLength));
            }
        }

        viewHolderHelper.setImageResource(R.id.iv_media_type, !TextUtils.isEmpty(playingAudioUrl) && !TextUtils.isEmpty(model.audio) && playingAudioUrl.equals(model.audio)
                && mp3Player != null && isPlaying ? R.drawable.stop_video_l : R.drawable.icon_media_audio);

        viewHolderHelper.setText(R.id.tv_current_time, DateTimeUtils.getMediaTimeNumber(model.progress / 1000));
        SeekBar seekBar = viewHolderHelper.getView(R.id.seekbar);
        seekBar.setProgress(model.progress);
        seekBar.setMax(model.max);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                model.progress = seekBar.getProgress();
                viewHolderHelper.setText(R.id.tv_current_time, DateTimeUtils.getMediaTimeNumber(seekBar.getProgress() / 1000));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    public static void goUserIndex(IView mView, int user_id) {
        //是3158账户，不做跳转
        if (user_id == 0) {
            return;
        }
        mView.advance(UserIndexActivity.class, user_id);
    }

    public static void goUserIndex(Activity mActivity, int user_id) {
        //是3158账户，不做跳转
        if (user_id == 0) {
            return;
        }

        Intent intent = new Intent(mActivity, UserIndexActivity.class);
        intent.putExtra("p0", user_id);
        mActivity.startActivity(intent);
    }


    /**
     * 初始化WebView
     */
    @SuppressLint("SetJavaScriptEnabled")
    public static void initWebView(WebView webView) {
        /**
         * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
         * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
         * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
         * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
         * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
         * setSupportZoom 设置是否支持变焦
         * */
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);// 设置支持javascript脚本
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 1.NARROW_COLUMNS：可能的话使所有列的宽度不超过屏幕宽度；2.NORMAL：正常显示不做任何渲染；3.SINGLE_COLUMN：把所有内容放大webview等宽的一列中
        // settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
        settings.setDisplayZoomControls(false);
        settings.setAllowFileAccess(true); // 启用或禁止WebView访问文件数据
        settings.setBuiltInZoomControls(false); //  隐藏缩放按钮
        settings.setSupportZoom(true); // 支持缩放
        // settings.setUseWideViewPort(true);// 可任意比例缩放
        settings.setLoadWithOverviewMode(true);//setUseWideViewPort方法设置webview推荐使用的窗口；设置webview加载的页面的模式
        settings.setGeolocationEnabled(true);// 启用地理定位
        settings.setDomStorageEnabled(true);
        settings.setSaveFormData(true);// 保存表单数据
        // settings.setSavePassword(true);
        // settings.setTextZoom(200);
        // settings.setMixedContentMode(1);
        // settings.setAcceptThirdPartyCookies();
        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }
        });
    }

    public static void setURL(WebView webView, String url) {
        webView.loadUrl(url);
    }

    /**
     * 设置需展示的Html片段
     */
    public static void setHtml(WebView webView, String protocol) {
        if (protocol != null) {
            webView.getSettings().setDefaultTextEncodingName("utf-8");
            webView.loadDataWithBaseURL(null, protocol, "text/html", "UTF-8", null);
        } else {
//            showMessage("未获取到内容,请稍后重试!");
        }
    }

    public static String toBase64(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();

        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }

    public static Bitmap toBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        int width = drawable.getIntrinsicWidth();
        width = width > 0 ? width : 1;
        int height = drawable.getIntrinsicHeight();
        height = height > 0 ? height : 1;

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }

    public static Bitmap decodeResource(Context context, int resId) {
        return BitmapFactory.decodeResource(context.getResources(), resId);
    }

    public static long getCurrentTime() {
        return System.currentTimeMillis();
    }

    public static File newRecordFile(Context cxt) {
        File dir = cxt.getExternalFilesDir(Environment.DIRECTORY_MOVIES);
        SimpleDateFormat sdf = new SimpleDateFormat("'sywbREC'_yyyyMMdd_HHmmss");
        String date = sdf.format(new Date());
        File file = new File(dir, date + ".mp4");
        return file;
    }

    /**
     * 复制文件到相册
     */
    public static void copyFileToDCIM(Context cxt, File file) {
        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        copyFile(cxt, file, new File(dir, file.getName()));

    }

    /**
     * 删除相册里的文件
     *
     * @param fileName 文件名字
     * @return
     */
    public static boolean delFileFromDCIM(String fileName) {
        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        return delFile(new File(dir, fileName));
    }

    /**
     * 删除文件
     */
    public static boolean delFile(File file) {
        if (file != null) {
            return file.delete();
        }
        return false;
    }

    /**
     * 复制文件
     */
    public static void copyFile(Context cxt, File from, File to) {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(from);
            os = new FileOutputStream(to);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
            cxt.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(to)));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void goConsult(final BasePresenter mPresenter, final IView mView, int project_id, int company_id, String cookie) {
        HttpUtils.getCode(project_id, company_id, new HttpCallback<String>(cookie) {

            @Override
            public void onStart() {
                super.onStart();
                mPresenter.onStartAsync();
            }

            @Override
            public void onSuccess(String s) {
                if (TextUtils.isEmpty(s)) {
                    return;
                }
                mView.advance(WebActivity.class, "畅谈通", s, data);
            }

            @Override
            public void onError(String strMsg) {
                super.onError(strMsg);
                mPresenter.showMessage(strMsg);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mPresenter.onFinishAsync();
            }

        });
    }

    /**
     * 生成一个startNum 到 endNum之间的随机数(不包含endNum的随机数)
     *
     * @param startNum
     * @param endNum
     * @return
     */
    public static int getNum(int startNum, int endNum) {
        if (endNum > startNum) {
            Random random = new Random();
            return random.nextInt(endNum - startNum) + startNum;
        }
        return 0;
    }

    /**
     * 生成一个0 到 count 之间的随机数
     *
     * @param endNum
     * @return
     */
    public static int getNum(int endNum) {
        if (endNum > 0) {
            Random random = new Random();
            return random.nextInt(endNum);
        }
        return 0;
    }
}
